const mongoose = require("mongoose");
const {Model} = require("mongoose");
class Base{
    constructor(schemaName,schema){
        this.schema=schema;
        this.schemaName=schemaName;
        this.models=new Map();
    }
    getModel(tenantId){
        
        console.log('tenantId  '+tenantId);
        const modeNames=this.schemaName+(tenantId ? '_' + tenantId : '');
        if(this.models.has(modeNames)){
            console.log('old  '+modeNames);
            return this.models.get(modeNames);
        }else{
            
            console.log('new  '+modeNames);
            const mymodel=mongoose.model(modeNames,this.schema,modeNames);
            this.models.set(modeNames,mymodel);
            return mymodel;
        }
    }
    async save(tenantId,option){
        let tanantmodel=this.getModel(tenantId);
        const doc= await tanantmodel.create(option);
        return doc;
    }
    async findById(tenantId,id){
        let tanantmodel=this.getModel(tenantId);
        return await tanantmodel.findById(id);
    }
    async findOne(tenantId,queryParam={},options={}){
        let tanantmodel=this.getModel(tenantId);
        return await tanantmodel.findOne(queryParam,options);
    }
    async findList(tenantId,queryParam,fields={},options={}){
        let tanantmodel=this.getModel(tenantId);
        return await tanantmodel.find(queryParam,fields,options);
    }
    async findOneAndUpdate(tenantId,queryParam,updateFields,options={}){
        return await this.getModel(tenantId).findOneAndUpdate(queryParam,updateFields,options);
    }
    async updateMany(tenantId,queryParam,updateFields,options={}){
        return await this.getModel(tenantId).updateMany(queryParam,updateFields,options);
    }
    async updateOne(tenantId,queryParam,updateFields,options={}){
        return await this.getModel(tenantId).updateMany(queryParam,updateFields,options);
    }
    async deleteOne(tenantId,queryParam,updateFields,options={}){
        return await this.getModel(tenantId).deleteOne(queryParam,updateFields,options);
    }
    async deleteMany(tenantId,queryParam,options={}){
        return await this.getModel(tenantId).updateOne(queryParam,options);
    }
}
module.exports=Base;